from dvadmin.utils.json_response import DetailResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from ops.devops.models import Module
from rest_framework import serializers
from dvadmin.utils.validator import CustomUniqueValidator


class ModuleSerializer(CustomModelSerializer):
    """
    devops-序列化器
    """
    module_name = serializers.CharField(max_length=50, validators=[CustomUniqueValidator(queryset=Module.objects.all(), message="模块名必须唯一1")])

    class Meta:
        model = Module
        fields = '__all__'
        read_only_fields = ["id"]


class ModuleViewSet(CustomModelViewSet):
    """
    devops接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    exclude_field = ['passwd']
    queryset = Module.objects.all()
    serializer_class = ModuleSerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["name"]

    def create(self, request, *args, **kwargs):
        # 获取post提交的body数据
        data = request.data

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        self.perform_create(serializer)
        return DetailResponse(data=serializer.data, msg="新增成功")
